package com.goods.InitializeTest.controller;

import com.goods.povos.CategoryPovo;
import com.goods.category.service.CategoryService;
import com.goods.utools.ipconversion.IPUtils;
import com.goods.utools.ipcustomer.IPCustomer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class TestController {
    @Autowired
    private CategoryService categoryService;

    @Resource
    private RedisTemplate<String, CategoryPovo> redisTemplate;

    @Resource
    private ListOperations<String, CategoryPovo> listOperations;

    @RequestMapping("/")
    public String gotoIndex(HttpServletRequest request, HttpSession session) {
//        获取请求的ip
        String ip = IPCustomer.getIpAddr(request);
        System.out.println(ip);
//        ip转地址
        String city = IPUtils.getCityInfo(ip);
        session.setAttribute("city", city);


//      首先查询redis
        List<CategoryPovo> categoryPovos = listOperations.range("categorypovos", 0, -1);
//       如果不存在则查询mysql
        if (categoryPovos == null || categoryPovos.size() == 0) {
            categoryPovos = categoryService.loadCategories();
//            并且放入redis
            if(categoryPovos!=null&&categoryPovos.size() != 0){
                listOperations.rightPushAll("categorypovos",categoryPovos);
            }

        }

        session.setAttribute("categorypovos", categoryPovos);
        return "index";
    }
}
